const Controller = require("../core/base");
const OSS = require('../tencent/tencentOSS');
const Model = require("../model/index");
const http = require("../http/index");

class CommonController extends Controller {
    // 小程序端登录
    async login() {
        const { ctx } = this;
        const body = ctx.request.body;
        try {
            let data = await http.getCode2Session(body, ctx);
            let userid = ""
            if(data) {
                const result = await Model.UserList.findOne({
                    where: {
                        openid: data.openid
                    }
                })

                if(!result) {
                    const { id } = await Model.UserList.create({
                        sessionKey: data.session_key,
                        openid: data.openid,
                        create_time: new Date(),
                        user_type: 1
                    })

                    userid = id;
                } else {
                    userid = result.id;
                }
            }

            this.success({
                ...data,
                userid
            })
        } catch(err) {
            this.fail(err);
        }
    }

    // 更新用户信息
    async udateUserInfo() {
        const { ctx } = this;
        const body = ctx.request.body;

        try {
            await Model.UserList.update({
                username: body.username,
                phone: body.phone,
                avatar: body.avatar,
                sex: body.sex
            }, {
                where: {
                    id: body.userid
                }
            })

            this.success();
        } catch(err) {
            this.fail(err);
        }
    }

    // 获取用户列表
    async userList() {
        const { ctx } = this;
        const body = ctx.request.query;
        const where = {};
        if(body.phone) {
            where.phone = body.phone;
        }
        try {
            const { count, rows } = await Model.UserList.findAndCountAll({
                attributes: ['id', 'username', 'phone', 'openid', 'create_time', 'user_type', 'avatar'],
                where: where,
                offset: (body.page - 1) * body.limit,
                limit: body.limit * 1
            })

            this.success({
                data: rows,
                total: count
            })
        } catch(err) {
            this.fail(err);
        }
    }

    // 获取上传token
    async getTencentToken() {
        const os = new OSS(this);
        try {
            const res = await os.getCredential();
            this.success(res);
        } catch(err) {
            this.fail(err);
        }
    }
}

module.exports = CommonController;